import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge, PageHeader, Tabs } from 'antd';
import '@/assets/css/settings';
import * as CheckManagementService from '../../../axios/CheckManagement'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import SearchForm from './SearchForm';
import ChooseBill from './ChooseBill';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

const { TabPane } = Tabs;
class ProcessQualityControl extends Component {
  state = {
    dataSource: [],
    visible: false,
    advanced: false,
    searchItem: {},
    activeKey: 0,
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 100,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '生产批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },

      {
        title: '产品机型',
        width: 100,
        dataIndex: 'model',
        sorter: (a, b) => compareString(a.model, b.model),
        // editable: true
      },
      {
        title: '总装车间',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'department',
        sorter: (a, b) => compareString(a.department, b.department)
      },
      {
        title: '装配班组',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'assembleProcess',
        sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess)
      },
      {
        title: '装配开始时间',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'testMachineProcess',
        sorter: (a, b) => compareDate(a.testMachineProcess, b.testMachineProcess)
      },
      {
        title: '质检人员',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'qualityCheckProcess',
        sorter: (a, b) => compareString(a.qualityCheckProcess, b.qualityCheckProcess)
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.create(1, record)}>分配</a>
        </>
      }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    btnLoading: false,
    modalTitle: '批量分配',
    modalType: 0,
    formData: {},
    chooseRecord: {},
  };
  componentDidMount() {
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.fetch()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize

    CheckManagementService.findCheckAssignAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  //0批量 1单独
  create = (type, record = {}) => {
    const { selectedRows } = this.state
    if (type === 0) {
      if (!selectedRows || !selectedRows.length) {
        openModalMessage('warning', '请选择要分配的单据！');
        return;
      }
    }
    this.setState({
      visible: true,
      modalTitle: type === 0 ? '批量分配' : '分配',
      modalType: type,
      chooseRecord: record
    });
  };

  handleCancel = e => {
    this.formChooseBill && this.formChooseBill.resetFields();
    this.setState({
      visible: false,
      selectedRowKeys: [],
      selectedRows: [],
      btnLoading: false
    });
    this.fetch();
  };


  handleSearch = value => {
    console.log(value)
    if (value.assembleStartDate && value.assembleStartDate.length === 2) {
      value.firstOutputDateMin = value.assembleStartDate[0].format('YYYY-MM-DD 00:00:00')
      value.firstOutputDateMax = value.assembleStartDate[1].format('YYYY-MM-DD 23:59:59')
      delete (value.assembleStartDate)
    }
    if (value.firstDeliveryDate && value.firstDeliveryDate.length === 2) {
      value.firstDeliveryDateMin = value.firstDeliveryDate[0].format('YYYY-MM-DD 00:00:00')
      value.firstDeliveryDateMax = value.firstDeliveryDate[1].format('YYYY-MM-DD 23:59:59')
      delete (value.firstDeliveryDate)
    }
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.batchNo) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.batchNo);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };
  chooseBill = () => {
    this.setState({ visible: true })
  }
  submitChooseBill = () => {
    this.formChooseBill.validateFields((err, value) => {
      if (err) return;
      console.log(value);
      let data = {}

      const { modalType, chooseRecord, selectedRows } = this.state;
      // 批量分配
      if (modalType == 0) {
        let arr = []
        for (var item of selectedRows) {
          arr.push(item.batchNo);
        }
        data.batchNo = arr
      }
      // 单独分配
      if (modalType == 1) {
        data.batchNo = [chooseRecord.batchNo]
      }

      this.setState({ btnLoading: true });
      // CheckManagementService.addCheckAssign(data).then(res => {
      //   this.setState({ btnLoading: false });
      //   if (res.data.code !== 200) {
      //     openModalMessage('warning', res.data.msg);
      //     return;
      //   }
      //   openSuccessModal(res.data.msg);
      //   this.handleCancel();
      // }).catch(err => {
      //   this.setState({ btnLoading: false });
      //   openModalMessage('error', err.message);
      // })
    })
  };

  downloadFather = () => {
    const { selectedRows } = this.state;

  }
  fetchAll = async () => {
    const { searchItem, total } = this.state
    searchItem.pageNum = 1
    searchItem.pageSize = total
    // let str = ''
    // for (var key in searchItem) {
    //   if (searchItem[key] || searchItem[key] === 0) {
    //     str += `&${key}=${searchItem[key]}`
    //   }
    // }
    await CheckManagementService.findCheckAssignAll(searchItem).then(res => {
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      const dataSourceAll = res.data.data.data
      const selectedRowKeys = dataSourceAll.map(item => item.batchNo);
      this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;
    const data = {}
    data.batchNo = [record.batchNo]
    data.model = record.model
    localStorage.setItem('ProcessQualityControl_searchItem', JSON.stringify(searchItem));
    localStorage.setItem('ProcessQualityControl_detailsList', JSON.stringify(data));
    // this.props.history.push({ pathname: "/ProcessQualityControl_Details", data: { record: data, searchItem } })
    this.props.history.push({ pathname: "/test", data: { record: data, searchItem } })
  }
  // SubPage1
  openSubPage = (url) => {
    const { searchItem } = this.state;
    localStorage.setItem('ProcessQuality_searchItem', JSON.stringify(searchItem));
    this.props.history.push({ pathname: url, data: { searchItem } })
  }

  onChangeTabs = activeKey => {
    this.setState({ activeKey });
  };
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({ searchItem: {} }, this.fetch);
  }
  render() {
    const { formData, loading, dataSource, advanced, columns, pageNum, pageSize, total, selectedRowKeys, visible, downloadLoading, searchItem, modalTitle, modalType, btnLoading } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.batchNo))) {
              keys.push(row.batchNo);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.batchNo), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <BasicLayout buttons={
          [
            <Button key={1} type="primary" onClick={() => this.create(0)} icon="arrow-right">分配</Button>,
            <Button key={2} type="primary" icon="printer">打印</Button>,
            <Button type="primary" key={7} onClick={() => this.openSubPage('/ProcessQuality_SubPage1')} icon="">机架水平精度</Button>,
            <Button type="primary" key={72} onClick={() => this.openSubPage('/ProcessQuality_SubPage2')} icon="">跳转2</Button>,
            <Button type="primary" key={73} onClick={() => this.openSubPage('/ProcessQuality_SubPage3')} icon="">跳转3</Button>,
            <Button type="primary" key={74} onClick={() => this.openSubPage('/ProcessQuality_SubPage4')} icon="">跳转4</Button>,
            <Button type="primary" key={75} onClick={() => this.openSubPage('/ProcessQuality_SubPage5')} icon="">跳转5</Button>,
            <Button type="primary" key={76} onClick={() => this.openSubPage('/ProcessQuality_SubPage6')} icon="">跳转6</Button>,
            <Button type="primary" key={77} onClick={() => this.openSubPage('/ProcessQuality_SubPage7')} icon="">跳转7</Button>,
            // <Button type="primary" key={8} onClick={this.openDetails} icon="">详情</Button>,
          ]} name="过程质量" icon="table">
          <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.batchNo}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowRowEdit
            allowEditable={this.loadData}
            rowSelection={rowSelection}
            onRow={(record, rowKey) => ({
              onClick: this.chooseRow.bind(this, record, rowKey)
            })}
          />
          <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
        </BasicLayout>

        <Modal
          visible={visible}
          destroyOnClose
          title={modalTitle}
          onOk={this.submitChooseBill}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
          confirmLoading={btnLoading}
        >
          <ChooseBill
            ref={node => (this.formChooseBill = node)}
            formData={formData}
          />
        </Modal>
      </div>
    );
  }
}
export default Form.create()(withRouter(ProcessQualityControl));